<?php

namespace App\Http\Controllers\Admin;



use App\Http\Model\City;


use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;


class CityController extends CommonController
{
    //get. admin/city
    public function index()
    {
        $city = City::all();

        return view('admin.city.index')->with('data',$city);
    }


    //post. admin/city  添加分类提交
    public function store()
    {
        //获取post表单提交过来的数据
        $input = Input::all();
        //$input = Input::except('_token');

        $rules = [
            'cityname' => 'required' ,

        ];
        $messages = [
            'cityname.required'=>'城市名不能为空',
        ];

        //设置验证规则并验证
        $validator = Validator::make($input,$rules,$messages);
        //判断验证是否通过
        if($validator->passes()){
            //将cityname转换为数组并依次存入数据库
            $input= explode('|',$input['cityname']);
            foreach ($input as $v){
                
                $re = City::create(array('cityname'=>$v));
            }
            if($re){
                return redirect('admin/city');
            }else{
                return back()->with('errors','添加失败，请稍后重试');
            }

        }else{
            //返回错误数据，并在前台接受
            return back()->withErrors($validator);
        }

    }
    //get. admin/city/create  添加分类
    public function create()
    {
        return view('admin.city.add');
    }
    //GET. admin/city/{city}/edit
    public function edit($ctid)
    {
        $field = City::find($ctid);
//        dd($field);
        return view('admin.city.edit',compact('field',$field));
    }
//PUT. admin/city/{city}
    public function update($ctid)
    {

        $input = Input::except('_token','_method');

        $rules = [
            'cityname' => 'required' ,

        ];

        $messages = [
            'cityname.required'=>'城市名不能为空',
        ];

        $validator = Validator::make($input,$rules,$messages);
        if($validator->passes()){

            $re = City::where('ctid',$ctid)->update($input);

            if($re){
                return redirect('admin/city');
            }else{
                return back()->with('errors','添加失败，请稍后重试');
            }

        }else{
            return back()->withErrors($validator);
        }

        return view('admin.city');
    }
// DELETE    admin/city/{city}   
    public function destroy($ctid)
    {
        $re = City::where('ctid',$ctid)->delete();
        if($re){
            $data=[
                'status' => 0,
                'msg' => '城市已删除！',
            ];
        }else{
            $data=[
                'status' => 1,
                'msg' => '城市删除失败！',
            ];
        }
        return $data;
    }



//GET.  admin/city/{city}
    public function show()
    {

        return view('admin.city');
    }


}
